import React, { createRef, PureComponent } from 'react'
import { message, Popconfirm, Select } from 'antd'
import { connect } from '@umijs/max'
import {
 InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import { AuthModal, ViewModal } from './page-components'
import styles from './index.less'

const { Option } = Select
const { OperateItem } = ProTableOperate

@connect(({ authApproval }) => ({ ...authApproval }))
class AuthApproval extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '申请人',
          dataIndex: 'userName',
          key: 'userName',
          width: '18%',
          // ellipsis: true,
        },
        {
          title: '申请API名称',
          dataIndex: 'apiName',
          width: '20%',
          key: 'apiName',
          // ellipsis: true,
        },
        {
          title: '状态',
          dataIndex: 'approveStatus',
          width: '18%',
          key: 'approveStatus',
          // ellipsis: true,
          render: (approveStatus) => (
            <>
              {
                approveStatus === 0 && (
                  <><i className="iconfont icon-daiban hu-blue" /> 待审批</>
                )
              }
              {
                approveStatus === 1 && (
                  <><i className="iconfont icon-chenggong hu-green" /> 已授权</>
                )
              }
              {
                approveStatus === 2 && (
                  <><i className="iconfont icon-caogao hu-gray" /> 已取消</>
                )
              }
              {
                approveStatus === 3 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 未通过</>
                )
              }
              {
                approveStatus === 4 && (
                  <><i className="iconfont icon-chehui hu-orange" /> 已撤回</>
                )
              }
            </>
          ),
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: '20%',
          key: 'applyTime',
          // ellipsis: true,
        },
        {
          title: '操作',
          key: 'action',
          render: (record) => {
            const {
              id, approveStatus,
            } = record
            return (
              <ProTableOptions>
                <span onClick={() => { this.view(record) }}>查看申请</span>
                {
                  // 后端-只有待审批状态下才能立即审批
                  (approveStatus === 0 || null) && (
                    <span onClick={() => { this.approve(record) }}>立即审批</span>
                  )
                }
                {
                  (approveStatus === 1 || null) && (
                    <Popconfirm
                      title="确认要取消授权吗？"
                      onConfirm={() => { this.handleOperateItem(id) }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <span>取消授权</span>
                    </Popconfirm>
                  )
                }
              </ProTableOptions>
            )
          },
        },
      ],
      approveStatus: '',
      searchName: '',
      forceUpdate: 0,
    }
    this.tableRef = createRef()
    this.authModalRef = createRef()
    this.viewModalRef = createRef()
  }

  handleOperateItem = (id) => {
    this.props.dispatch({
      type: 'authApproval/queryCancelUserApiAuthById',
      params: {
        id,
      },
      cb: (res) => {
        const { status, msg } = res || {}
        if (status === 200) {
          message.success('操作成功')
          this.forceUpdateFn()
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  fetchData = () => {
    const { approveStatus, searchName, query } = this.state
    this.tableRef?.current?.resetPageNum()
    const tempQuery = {}
    tempQuery.searchName = searchName
    tempQuery.approveStatus = approveStatus || ''
    this.setState({
      query: {
        ...query,
        ...tempQuery,
      },
    })
  }

  view = (record) => {
    this.viewModalRef?.current?.toggleModal(record)
  }

  approve = (record) => {
    this.authModalRef?.current?.toggleModal(record)
  }

  forceUpdateFn = () => {
    this.setState((prevState) => ({
      forceUpdate: prevState.forceUpdate + 1,
    }))
  }

  render() {
    const {
      columns, loading, query, forceUpdate, approveStatus,
    } = this.state
    return (
      <div className={styles.auth_approval}>
        <ProTableOperate style={{ marginTop: 0 }}>
          <OperateItem align="left">
            <span>任务状态</span>
            <Select
              allowClear
              value={approveStatus}
              onChange={(value) => {
                this.setState({
                  approveStatus: value,
                }, () => { this.fetchData() })
              }}
            >
              <Option key="0" value="0">待审批</Option>
              <Option key="1" value="1">已授权</Option>
              <Option key="2" value="2">已取消</Option>
              <Option key="3" value="3">未通过</Option>
              <Option key="4" value="4">已撤回</Option>
            </Select>
          </OperateItem>
          <OperateItem align="left">
            <InputSearch
              placeholder="请输入用户名或API进行搜索"
              onChange={(e) => {
                this.setState({
                  searchName: e.target.value,
                })
              }}
              onSearch={this.fetchData}
            />
          </OperateItem>
        </ProTableOperate>
        <ProTable
          ref={this.tableRef}
          loading={loading}
          key={forceUpdate}
          url="/api/v1/dataApiAuthApprove/getApiAuthApprovePage"
          query={query}
          rowKey="id"
          columns={columns}
        />
        <AuthModal ref={this.authModalRef} forceUpdateFn={this.forceUpdateFn} />
        <ViewModal ref={this.viewModalRef} />
      </div>
    )
  }
}

export default AuthApproval
